package com.kingmed.kmss.admin.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kingmed.kmss.admin.modules.ums.model.UmsAdmin;
import com.kingmed.kmss.admin.modules.ums.model.UmsOrganization;
import com.kingmed.kmss.admin.modules.ums.service.UmsAdminService;
import com.kingmed.kmss.admin.modules.ums.service.UmsOrganizationService;
import com.kingmed.kmss.common.annotation.IgnoreCommonResponseAdvice;
import com.kingmed.kmss.common.dto.admin.ums.*;
import com.kingmed.kmss.common.enums.admin.OrgLevel;
import com.kingmed.kmss.common.utils.BeanCopyUtils;
import com.kingmed.kmss.common.vo.CommonResponse;
import com.kingmed.kmss.common.vo.CommonResponseHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 对外提供，包括：场景1微服务之间，场景2对外围系统
 * 强制：必须要跟前端的接口分开，前端页面绝对不能调用此包里的接口，因为此包接口没有权限注解
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("/ext/ums")
@Api(tags = "用户管理-对外接口")
public class RemoteAdminController {

    @Autowired
    private UmsOrganizationService orgService;

    @Autowired
    private UmsAdminService adminService;

    @ApiOperation("外部调用-loginCheck根据用户名密码进行统一的用户登录验证，返回AdminAuthDTO")
    @PostMapping(value = "/loginCheck")
    public CommonResponse<AdminAuthDTO> loginCheck(@RequestBody AdminLoginDTO adminLoginDto) {
        AdminAuthDTO adminAuthDto = adminService.loginCheck(adminLoginDto.getUsername(), adminLoginDto.getPassword());
        log.info("loginCheck in RemoteAdminController:" + adminAuthDto);
        if (adminAuthDto == null) {
            return CommonResponseHelper.unauthorized("用户名或者密码错误");
        }
        return CommonResponseHelper.success(adminAuthDto);
    }

    @ApiOperation("外部调用-OA登录获取登录用户信息")
    @GetMapping(value = "/oaLoginQuery")
    public CommonResponse<AdminAuthDTO> oaLoginQuery(@RequestParam String loginId) {
        AdminAuthDTO adminAuthDto = adminService.oaLogin(loginId);
        log.info("oaLogin in RemoteAdminController:" + adminAuthDto);
        return CommonResponseHelper.success(adminAuthDto);
    }

    @ApiOperation("外部调用-根据OA用户查询用户信息")
    @GetMapping(value = "/queryAdminByOAID")
    public CommonResponse<AdminAuthDTO> queryAdminByName(@RequestParam String oaLoginId) {
        return CommonResponseHelper.success(adminService.getAdminByOaLoginId(oaLoginId));
    }

    @ApiOperation(value = "外部调用-根据员工号、用户名、姓名查询用户基础信息")
    @PostMapping(value = "/queryByCondition")
    @ResponseBody
    public CommonResponse<List<AdminDTO>> queryByCondition(@RequestBody AdminQueryDTO queryDTO) {
        return CommonResponseHelper.success(adminService.queryByCondition(queryDTO));
    }

    /**
     * 如果不想返回通用结果对象，需要添加此注解IgnoreCommonResponseAdvice
     */
    @ApiOperation("外部调用-根据orgId获取下级组织")
    @IgnoreCommonResponseAdvice
    @GetMapping(value = "/getOrgAndChild")
    public String getOrgAndChild(@RequestParam("orgId") Long orgId) {
        return orgService.selfAndChildString(orgId);
    }

    @ApiOperation("外部调用-根据orgId获取下级组织树")
    @GetMapping(value = "/orgAndChildTree")
    public OrgNodeDTO orgAndChildTree(@RequestParam("orgId") Long orgId) {
        return orgService.tree(orgId);
    }

    @ApiOperation("外部调用-根据orgId获取下级组织列表")
    @GetMapping(value = "/orgAndChild")
    public List<OrgNodeDTO> orgAndChild(@RequestParam("orgId") Long orgId) {
        return orgService.selfAndChild(orgId);
    }

    @ApiOperation("外部调用-根据orgId获取所有上级组织列表")
    @IgnoreCommonResponseAdvice
    @GetMapping(value = "/getParentUpList")
    public List<UmsOrganization> getParentUpList(@RequestParam("orgId") Long orgId) {
        return orgService.getParentUpList(orgService.loadAllOrg(), orgId);
    }

    @ApiOperation("外部调用-根据子公司ID查询大区信息")
    @IgnoreCommonResponseAdvice
    @GetMapping(value = "/getRegionByBranchId")
    public OrganizationDTO getRegionByBranchId(@RequestParam("branchId") Long branchId) {
        List<UmsOrganization> orgList = orgService.getParentUpList(orgService.loadAllOrg(), branchId);
        if (CollectionUtils.isEmpty(orgList)) {
            return null;
        }
        for (UmsOrganization organization : orgList) {
            if (OrgLevel.REGION.getCode().equals(organization.getLevel())) {
                return BeanCopyUtils.copy(organization, OrganizationDTO.class);
            }
        }
        return null;
    }

    @ApiOperation("外部调用-获取所有子公司")
    @GetMapping(value = "/getAllSubsidiary")
    @IgnoreCommonResponseAdvice
    public List<OrganizationDTO> getAllSubsidiary() {
        return orgService.getAllSubsidiary();
    }

    @ApiOperation("外部调用-根据OrgID批量查询组织信息")
    @PostMapping(value = "/getOrgByIds")
    @IgnoreCommonResponseAdvice
    public Map<Long, OrganizationDTO> getOrgByIds(@RequestBody List<Long> orgIds) {
        return orgService.getOrgByIds(orgIds);
    }

    @ApiOperation("外部调用-根据组织ID获取组织详细信息")
    @IgnoreCommonResponseAdvice
    @GetMapping(value = "/queryOrgById")
    public OrganizationDTO queryOrgById(@RequestParam("orgId") Long orgId) {
        return BeanCopyUtils.copy(orgService.getBaseMapper().selectById(orgId), OrganizationDTO.class);
    }

    @ApiOperation("外部调用-根据ID查询用户信息")
    @GetMapping(value = "/getUserById")
    public CommonResponse<AdminDTO> getUserById(@RequestParam String id) {
        UmsAdmin admin = adminService.getBaseMapper().selectOne(new QueryWrapper<UmsAdmin>().lambda().eq(UmsAdmin::getId, id));
        return CommonResponseHelper.success(BeanCopyUtils.copy(admin, AdminDTO.class));
    }


    @ApiOperation("外部调用-根据员工工号查询用户信息")
    @PostMapping(value = "/listEmployeeNum")
    public CommonResponse<List<AdminDTO>> listEmployeeNum(@RequestBody List<String> employeeNumList) {
        List<UmsAdmin> adminList = adminService.getBaseMapper().selectList(new QueryWrapper<UmsAdmin>().lambda().in(UmsAdmin::getEmployeeNum, employeeNumList));
        return CommonResponseHelper.success(BeanCopyUtils.copyList(adminList, AdminDTO.class));
    }

    @ApiOperation("外部模块调用-根据员工号获取相关的信息（角色权限），用于对外接口的数据权限控制")
    @PostMapping(value = "/loadAdminAuthDtoByUsernameNew")
    public CommonResponse<AdminAuthDTO> loadAdminAuthDtoByUsernameNew(@RequestBody AdminLoginDTO adminLoginDto) {
        AdminAuthDTO adminAuthDto = adminService.loadAdminAuthDtoByUsernameNew(adminLoginDto.getUsername());
        log.info("loadAdminAuthDtoByUsername in RemoteAdminController:" + adminAuthDto);
        if (adminAuthDto == null) {
            return CommonResponseHelper.unauthorized("未找到对应员工号的用户");
        }
        return CommonResponseHelper.success(adminAuthDto);
    }
}
